<template lang="pug">
  .datatables-wrapper
    //- 表格头部前置插入
    slot(name="prepend")
    //- 表格头部
    slot(name="header")
      .datatables-header.clearfix
        ButtonList(
          v-if="toolbarList && toolbarList.length > 0"
          class="toolbar"
          :buttonList="toolbarList")
        slot(
          class="customToolbar"
          name="toolbar")
        FilterBox(
          v-if="filterList && filterList.length > 0"
          class="filter-box"
          :columns="columns"
          :filterList="filterList"
          :filterBy="filterBy"
          @changeFilterBy="changeFilterBy")
    DataTableBody.datatables-body(
      ref="dataTableBody"
      :isLoading="isLoading"
      :tableList="tableList"
      :operationList="operationList"
      :operationWidth="operationWidth"
      :columns="columns"
      :tableData="currentData"
      :orderBy="orderBy"
      :fullTableWidth="true"
      @changeOrderBy="changeOrderBy")
    //- 表格底部
    slot(name="footer")
      .datatables-footer.clearfix
        //- 表格底部的列显示器
        slot(name="viewer")
          ColumnFilter.datatables-viewer(
            v-if="viewerList.length > 0"
            class="column-filter"
            :columnsObject="columns"
            :tableList="tableInitList"
            :columnGroupBy="columnGroupBy"
            :tableFullList="tableFullList"
            :openDirection=2
            @grandSonEvent="changeTableList")
        //- 表格底部的分页组件
        slot(name="page")
          el-pagination.datatables-page(
            background
            class="pagination"
            layout="total, sizes, prev, pager, next"
            :page-sizes="[10, 25, 50, 100]"
            :page-size="pageSize"
            :current-page="pageIndex"
            :total="recordsFiltered"
            @size-change="pageSizeChange"
            @current-change="pageIndexChange")
    //- 表格底部后置插入
    slot(name="append")
</template>
<script>

import { reduce, orderBy, slice, iteratee } from 'lodash'

import SmartDialog from '@/components/SmartDialog'
import SmartForm from '@/components/SmartForm'
import DataTableBody from '@/components/DataTable/Body'
import ButtonList from '@/components/ButtonList'
import FilterBox from '@/components/FilterBox'
import ColumnFilter from '@/containers/DataTablePage/columnFilter'
import PrintTable from '@/components/PrintTable'
import ExcelTable from '@/components/ExcelTable'

export default {
  name: 'DataTablePage',
  components: {
    SmartDialog,
    SmartForm,
    DataTableBody,
    ButtonList,
    FilterBox,
    ColumnFilter,
    PrintTable,
    ExcelTable
  },
  props: {
    ajax: {
      type: String | Object
    }, // 远程数据源
    serverSide: {
      type: Boolean,
      default: false
    }, // 是否服务端分页、查询、排序，当有远程数据源的时候有用
    tableData: {
      type: Array,
      default: () => ([])
    }, // 数据，当没有远程数据源的时候，直接读数据
    columns: {
      type: Object,
      default: () => ({})
    }, // 表格内所有的字段定义
    toolbarList: {
      type: Array,
      default: () => ([])
    },
    operationList: {
      type: Array,
      default: () => ([])
    },
    operationWidth: {
      type: Number,
      default: 0
    },
    columnGroupBy: {
      type: Array,
      default: () => ([])
    },
    tableInitList: {
      type: Array,
      default: () => ([])
    },
    tableFullList: {
      type: Array,
      default: () => ([])
    },
    filterInitList: {
      type: Array,
      default: () => ([])
    },
    viewer: {
      type: Object,
      default: () => ({})
    },
    viewerList: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    return {
      isAjax: !!this.ajax,
      filterList: this.filterInitList,
      data: this.tableData,
      tableList: this.tableInitList,
      orderBy: [],
      filterBy: {},
      pageSize: 10,
      pageIndex: 1,
      isLoading: false
    }
  },
  computed: {
    filteredData () {
      const result = reduce(this.filterBy, (a, value, key) => {
        const filtered = a.filter(item => {
          if (this.columns[key].filter.type === 'input') {
            if (this.columns[key].filter.like) {
              return item[key].indexOf(value) >= 0
            } else {
              return value === item[key]
            }
          }
          return true
        })
        return filtered
      }, this.data)
      return result
    },
    currentData () {
      const data = orderBy(this.filteredData, this.orderBy.map(iteratee('name')), this.orderBy.map(iteratee('sort')))
      const result = this.pageIndex * this.pageSize
      return slice(data, result - this.pageSize, result)
    },
    recordsFiltered () {
      return this.filteredData.length
    },
    recordsTotal () {
      return this.data.length
    }
  },
  methods: {
    pageSizeChange (value) {
      this.pageSize = value
      this.pageIndexChange(1)
    }, /* 每页显示记录数的修改函数 */
    pageIndexChange (value) {
      this.$refs['dataTableBody'].y = 0
      this.pageIndex = value
    }, /* 当前页码的修改函数 */
    changeOrderBy (value) {
      this.orderBy = value
    },
    changeFilterBy (value) {
      this.filterBy = value
      // this.getData()
    },
    getData (value) {
      this.$refs.dataTableBody.updateY(0)
      this.isLoading = true
      this.$get({
        url: this.ajax,
        params: {
          orderBy: this.orderByToOrderText(this.orderBy),
          filterBy: this.filterByToFilterText({...this.filterBy, ...this.filterByAlways}),
          pageSize: this.isTree ? 999999 : this.pageSize,
          pageIndex: this.isTree ? 1 : this.pageIndex,
          data: this.requestData
        }
      }).then((data) => {
        const result = data || {
          data: [],
          recordsFiltered: 0,
          recordsTotal: 0
        }
        this.data = result.data
        this.recordsFiltered = result.recordsFiltered
        this.recordsTotal = result.recordsTotal
      }).catch(() => {
        this.isLoading = false
      })
      // this.getData()
    },
    // getRelation (value) {
    //   this.isLoading = true
    //   this.$getRelation({
    //     relations: this.relationKeys.join(',')
    //   })
    //   .then((data) => {
    //     Object.keys(this.columnsList).map(key => {
    //       const relation = this.columnsList[key].relation
    //       if (data[relation]) {
    //         this.columnsList[key].options = [...this.columnsList[key].optionsInit || [], ...data[relation]].map(option => {
    //           const label = option[this.columnsList[key].labelName || 'label']
    //           // const subtextKey = this.columnsList[key].subtext || 'subtext'
    //           // const subtext = subtextKey === 'pinyin' ? pinyinInitial(label) : option[subtextKey]
    //           return {
    //             value: option.value !== undefined ? option.value : option.id,
    //             label,
    //             // subtext,
    //             ...option
    //           }
    //         })
    //       }
    //     })
    //     this.isLoading = false
    //     this.isFilterShow = true
    //     this.$emit('getRelation', this.columnsList)
    //     this.getData()
    //   }).catch(() => {
    //     this.isLoading = false
    //   })
    // }, /* 获取当前资源所关联的数据，并填到对应的列里 */
    changeTableList (value) {
      this.tableList = value
    }, /* 列过滤 */
    filterByToFilterText (filterValues) {
      let filterBy = []
      Object.keys(filterValues).map(key => {
        // filterby的字段需要设置columns的filter
        if (this.columnsList[key]) {
          const columnFilter = this.columnsList[key].filter
          if (columnFilter.type === 'daterange') {
            filterBy.push({
              name: key,
              type: 'ge',
              value: filterValues[key][0]
            })
            filterBy.push({
              name: key,
              type: 'le',
              value: filterValues[key][1]
            })
          } else {
            let type = typeof (columnFilter.filterType) === 'undefined' ? 'eq' : columnFilter.filterType
            if (columnFilter.like) {
              type = 'like'
            }
            filterBy.push({
              name: key,
              type: type,
              value: filterValues[key]
            })
          }
        }
      })
      const result = filterBy.filter(item => {
        return item.value !== '' && item.value !== undefined && item.value !== null
      })
      return result.map(({name, type, value}) => `${name}|${type}|${value}`).join(';')
    },
    orderByToOrderText (orderBy) {
      return orderBy.map(({name, sort}) => `${name}|${sort}`).join(';')
    },
    orderTextToOrderBy (orderText) {
      if (!orderText) {
        return []
      }
      return orderText.split(';').map(item => {
        const order = item.split('|')
        return {
          name: order[0],
          sort: order[1]
        }
      })
    }
  }
}
</script>

<style scoped lang="sass">
.datatables-wrapper
  display: flex
  flex-direction: column
  flex: 1
  height: 100%
.datatables-header
  margin-bottom: 10px
  position: relative
  z-index: 200
  .datatables-toolbar
    float: left
    margin-right: 12px
  .datatables-filter
    float: right
    margin-left: 12px
.datatables-body
  display: flex
  flex-direction: column
  flex: 1
  z-index: 100
.datatables-footer
  display: flex
  justify-content:  space-between
  align-item: center
  position: relative
  z-index: 300
  .datatables-page
    flex: 1
    padding-top: 12px
    text-align: right
  .datatables-viewer
    float: left
    padding-top: 12px
</style>
